package doublepointer;

/**
 * Created by lh on 2019/7/22.
 * 题目描述：
 * 归并两个有序数组，把归并结果存到第一个数组上
 *
 * Example:
 * Input:
 * nums1 = [1,2,3,0,0,0], m = 3
 * nums2 = [2,5,6],       n = 3
 *
 * Output: [1,2,2,3,5,6]
 */
public class MergeArray {
    public static int[] merge(int[] nums1, int m, int[] nums2, int n) {
        int[] nums = new int[m + n];
        int index = m + n - 1;
        int i = m - 1, j = n - 1;
        while (i >= 0 || j >= 0) {
            if (i < 0) {
                nums[index--] = nums2[j--];
            } else if (j < 0) {
                nums[index--] = nums1[i--];
            } else if (nums1[i] > nums2[j]) {
                nums[index--] = nums1[i--];
            } else {
                nums[index--] = nums2[j--];
            }
        }
        return nums;
    }
}
